﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;


namespace ywxt.NewsPush.Controllers.Qualification
{
    using NHibernate;
    using NHibernate.Criterion;
    using NHibernate.Linq;
    using DB_NH;
    using System.IO;

    public class QualificationDetailController : Controller
    {
        //
        // GET: /Qualification/

        public ActionResult Index()
        {
            return View();
        }

        #region 列表页面

        public ActionResult QualificationDetailList()
        {
            return View();
        }

        #endregion

        #region 修改/添加的页面
        /// <summary>
        /// 显示修改/添加的页面
        /// </summary>
        /// <param name="DetailId">传入的ID值，如果传递的数据为空，新生成一个ID</param>
        /// <returns></returns>
        public ActionResult QualificationDetail(string DetailId)
        {
            //编辑修改
            if (DetailId != null && DetailId != "" && DetailId != "0")
            {
                ViewBag.Id = DetailId;
            }
            //新增
            else
            {
                ViewBag.Id = ywxt.Common.Common.NewID();
            }

            return View();
        }

        #endregion

        #region 添加企业资质记录

        /// <summary>
        /// 添加企业资质记录
        /// </summary>
        /// <param name="VmQualificationDetail"></param>
        /// <returns></returns>
        public JsonResult AddQualificatonDetail(Models.Qualification.VmQualificationDetail VmQualificationDetail)
        {
            var _returnValue = new Models.clsCommonJsonResult();

            var sessionFactory = DB_NH.SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                try
                {
                    #region 验证信息

                    string _this_user_name_en = ywxt.Common.Common.getAuthenticatedUser(User).Name;
                    string _this_user_name_cn = ywxt.Common.Common.getAuthenticatedUser(User).DisplayName;

                    //查询操作用户
                    var _user =
                        (from u in session.Query<DB_NH.DB_Model.ywxt.t_sys_user>()
                         where u.is_valid == 1
                         && u.user_truename_cn == _this_user_name_cn
                         && u.user_truename_en == _this_user_name_en
                         select u)
                        .FirstOrDefault();

                    //核对有没有该操作用户信息
                    if (_user == null) throw new Exception("没有该操作用户，请认真核对信息");

                    //查询资质主表
                    var _qualification =
                       (from a in session.Query<DB_NH.DB_Model.Qualification.Qualification>()
                        where a.IsValid == 1
                        && a.Id == VmQualificationDetail.Qid
                        select a)
                        .FirstOrDefault();

                    #endregion


                    #region  初始化一个企业资质表DBModel 的一个对象_qualification，并填充数据
                    var _qualificationDetail = new DB_NH.DB_Model.Qualification.QualificationDetails()
                    {
                        //关联的主表
                        Qualification = _qualification,

                        //资质要求
                        Details_Require = VmQualificationDetail.Details_Require,

                        //业务范围
                        Details_Range = VmQualificationDetail.Details_Range,

                        //备注
                        Details_Remark = VmQualificationDetail.Details_Remark
                    };

                    #endregion

                    //保存企业资质明细表
                    session.SaveOrUpdate(_qualificationDetail);

                    //事务提交
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    //异常处理，并返回错误信息
                    if (transaction.IsActive) transaction.Rollback();
                    _returnValue.ISOK = false;
                    _returnValue.MESSAGE = ex.Message;
                }
            }
            //返回Json数据
            return Json(_returnValue);
        }

        #endregion

        #region 删除企业资质明细记录
        /// <summary>
        /// 删除企业资质记录
        /// </summary>
        /// <param name="DetailId">企业资质记录明细id</param>
        /// <returns></returns>
        public JsonResult deleteQualificationDetailData(string DetailId)
        {
            var _returnValue = new Models.clsCommonJsonResult();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                try
                {
                    #region 验证信息

                    //获取当前登录用户名称
                    string _this_user_name_en = ywxt.Common.Common.getAuthenticatedUser(User).Name;
                    string _this_user_name_cn = ywxt.Common.Common.getAuthenticatedUser(User).DisplayName;

                    //查询操作用户
                    var _user =
                        (from u in session.Query<DB_NH.DB_Model.ywxt.t_sys_user>()
                         where u.is_valid == 1
                         && u.user_truename_cn == _this_user_name_cn
                         && u.user_truename_en == _this_user_name_en
                         select u)
                        .FirstOrDefault();

                    //核对有没有该操作用户信息
                    if (_user == null) throw new Exception("没有该操作用户，请认真核对信息");


                    //查询企业资质明细记录
                    var _qualificationDetail =
                       (from p in session.QueryOver<DB_NH.DB_Model.Qualification.QualificationDetails>()
                        where p.IsValid == 1
                        && p.Id == DetailId
                        select p)
                       .SingleOrDefault();

                    //核对有没有该企业资质明细记录
                    if (_qualificationDetail == null) throw new Exception("没有该企业资质明细记录，请认真核对信息");

                    #endregion


                    #region 删除企业资质明细记录

                    _qualificationDetail.IsValid = 0;

                    _qualificationDetail.Details_Remark += "(" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + " 由用户" + _user.user_truename_cn + "删除)";

                    session.SaveOrUpdate(_qualificationDetail);


                    #endregion

                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    if (transaction.IsActive) transaction.Rollback();
                    _returnValue.ISOK = false;
                    _returnValue.MESSAGE = ex.Message;
                }
            }

            return Json(_returnValue);
        }
        #endregion

        #region 企业资质记录明细列表的JSON类定义
        /// <summary>
        /// 企业资质记录明细列表的JSON类定义
        /// </summary>
        public class JSONClassForQualificationDetail : Models.clsCommonJsonResult
        {
            public List<Models.Qualification.VmQualificationDetail> VmQualificationDetails { get; set; }

            public JSONClassForQualificationDetail()
            {
                VmQualificationDetails = new List<Models.Qualification.VmQualificationDetail>();
            }
        }
        #endregion

        #region 查询企业资质记录明细列表
        /// <summary>
        /// 根据关键字 keyword,获取企业资质明细记录列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public JsonResult GetQualificationDetailList(string keyword, int pagesize, int pageindex)
        {
            var _returnValue = new JSONClassForQualificationDetail();
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                try
                {
                    //根据kword查出相应的列表
                    var _qualificationDetail =
                    (from v in session.Query<DB_NH.DB_Model.Qualification.QualificationDetails>()
                     where v.IsValid == 1
                     && v.Details_Require.Contains(keyword)         //根据资质要求查询
                     orderby v.CreateDate descending
                     select new Models.Qualification.VmQualificationDetail()
                     {
                         DetailId = v.Id,
                         Qid = v.Qualification.Id,
                         Type = v.Qualification.Type,
                         Details_Require = v.Details_Require,
                         Details_Range = v.Details_Range,
                         Details_Remark = v.Details_Remark

                     }).ToList();

                    //计算查询的总记录数
                    _returnValue.RecordCount = _qualificationDetail.Count();

                    if (pagesize > 0 && pagesize > 0 && _returnValue.RecordCount > 0)
                    {
                        _returnValue.PageCount = _returnValue.RecordCount % pagesize == 0 ? _returnValue.RecordCount / pagesize : (_returnValue.RecordCount / pagesize + 1);

                        if (pageindex < 0)
                        {
                            pageindex = 0;
                        }
                        else if (pageindex >= _returnValue.PageCount)
                        {
                            pageindex = _returnValue.PageCount - 1;
                        }

                        _returnValue.PageIndex = pageindex;

                        _returnValue.VmQualificationDetails = _qualificationDetail
                            .Skip(pageindex * pagesize)
                            .Take(pagesize)
                            .ToList();
                    }
                    else
                    {
                        _returnValue.PageCount = 1;
                        _returnValue.PageIndex = 0;

                        _returnValue.VmQualificationDetails = _qualificationDetail
                            .ToList();
                    }

                    transaction.Commit();
                }
                catch (Exception _ex)
                {
                    if (transaction.IsActive) transaction.Rollback();
                    _returnValue.ISOK = false;
                    _returnValue.MESSAGE = _ex.Message;
                }
            }
            return Json(_returnValue);
        }
        #endregion

        #region 修改的企业资质明细记录的JSON类定义
        /// <summary>
        /// 企业资质明细记录的JSON类定义
        /// </summary>
        public class JSONClassForOneQualificationDetail : Models.clsCommonJsonResult
        {
            public Models.Qualification.VmQualificationDetail VmQualificationDetail { get; set; }

        }
        #endregion

        #region 修改企业资质明细记录

        /// <summary>
        /// 修改企业资质记录
        /// </summary>
        /// <param name="VmQualificationDetail"></param>
        /// <returns></returns>
        public JsonResult updateQualificationDetail(Models.Qualification.VmQualificationDetail VmQualificationDetail)
        {
            var _returnValue = new Models.clsCommonJsonResult();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                try
                {
                    #region 验证信息

                    string _this_user_name_en = ywxt.Common.Common.getAuthenticatedUser(User).Name;
                    string _this_user_name_cn = ywxt.Common.Common.getAuthenticatedUser(User).DisplayName;

                    //查询操作用户
                    var _user =
                        (from u in session.Query<DB_NH.DB_Model.ywxt.t_sys_user>()
                         where u.is_valid == 1
                         && u.user_truename_cn == _this_user_name_cn
                         && u.user_truename_en == _this_user_name_en
                         select u)
                        .FirstOrDefault();

                    //核对有没有该操作用户信息
                    if (_user == null) throw new Exception("没有该操作用户，请认真核对信息");

                    #endregion

                    #region  初始化一个企业资质明细表DBModel 的一个对象_qualificationDetail

                    var _qualificationDetail = (from p in session.QueryOver<DB_NH.DB_Model.Qualification.QualificationDetails>()
                                                where p.IsValid == 1
                                                && p.Id == VmQualificationDetail.DetailId
                                                select p
                              ).SingleOrDefault();

                    _qualificationDetail.Details_Require = VmQualificationDetail.Details_Require;
                    _qualificationDetail.Details_Range = VmQualificationDetail.Details_Range;
                    _qualificationDetail.Details_Remark = VmQualificationDetail.Details_Remark;

                    #endregion

                    //保存企业资质表
                    session.SaveOrUpdate(_qualificationDetail);

                    //事务提交
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    //异常处理，并返回错误信息
                    if (transaction.IsActive) transaction.Rollback();
                    _returnValue.ISOK = false;
                    _returnValue.MESSAGE = ex.Message;
                }
            }
            //返回Json数据
            return Json(_returnValue);
        }

        #endregion

        #region 根据id查询需要编辑的那一条企业资质明细记录信息
        /// <summary>
        /// 根据关键字 id,获取需要编辑的那一条企业资质明细记录信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult GetOneQualificationDetail(string DetailId)
        {
            var _returnValue = new JSONClassForOneQualificationDetail();
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                //获取需要编辑的那一条企业资质明细记录信息
                try
                {

                    //根据id查出相应的列表
                    var _qualificationDetail =
                        (from v in session.Query<DB_NH.DB_Model.Qualification.QualificationDetails>()
                         where v.IsValid == 1
                         && v.Id == DetailId
                         orderby v.CreateDate descending
                         select new Models.Qualification.VmQualificationDetail()
                         {
                             DetailId = v.Id,
                             Qid = v.Qualification.Id,
                             Type = v.Qualification.Type,
                             Details_Require = v.Details_Require,
                             Details_Range = v.Details_Range,
                             Details_Remark = v.Details_Remark

                         }).Take(1).FirstOrDefault();

                    _returnValue.VmQualificationDetail = _qualificationDetail;

                    transaction.Commit();

                }
                catch (Exception _ex)
                {
                    if (transaction.IsActive) transaction.Rollback();
                    _returnValue.ISOK = false;
                    _returnValue.MESSAGE = _ex.Message;
                }
            }
            return Json(_returnValue);
        }
        #endregion
    }
}